﻿/* 
 * Since 2008 - 2012
 */

package com.hh.bss.project.service.impl;

import java.util.ArrayList;
import java.util.Date;
import java.util.List;

import org.springframework.dao.DataAccessException;
import org.springframework.jdbc.core.RowMapper;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;

import com.hh.bss.auth.client.OnlineUser;
import com.hh.bss.base.BaseBusinessService;
import com.hh.bss.base.EntityDao;
import com.hh.bss.common.MapObjectRowMapper;
import com.hh.bss.common.cache.SystemUserCache;
import com.hh.bss.common.page.Page;
import com.hh.bss.customer.dao.CompanyDao;
import com.hh.bss.customer.dao.CompanyDeptDao;
import com.hh.bss.customer.dao.CompanyDeptTitleDao;
import com.hh.bss.customer.entity.Company;
import com.hh.bss.customer.entity.CompanyCv;
import com.hh.bss.customer.entity.CompanyDept;
import com.hh.bss.customer.entity.CompanyDeptTitle;
import com.hh.bss.project.dao.SearchProjectCvDao;
import com.hh.bss.project.entity.ContractJobSearchProject;
import com.hh.bss.project.entity.SearchProjectCv;
import com.hh.bss.project.entity.SearchProjectInterview;
import com.hh.bss.project.service.SearchProjectCvService;
import com.hh.bss.project.vo.query.SearchProjectCvQuery;
import com.hh.bss.talent.dao.CvDao;
import com.hh.bss.talent.entity.Cv;
import com.hh.bss.talent.service.CvService;


@Service
@Transactional
public class SearchProjectCvServiceImpl extends BaseBusinessService<SearchProjectCv,java.lang.Integer>  implements SearchProjectCvService<SearchProjectCv,java.lang.Integer>{

	private SearchProjectCvDao searchProjectCvDao;
	/**增加setXXXX()方法,spring就可以通过autowire自动设置对象属性,请注意大小写*/
	private CompanyDao companyDao;
	private CompanyDeptDao companyDeptDao;
	private CompanyDeptTitleDao companyDeptTitleDao;
	private CvService cvService;
	private CvDao cvDao;
	public void setCvDaoImpl(CvDao dao) {
		this.cvDao = dao;
	}
	public void setCvServiceImpl(CvService service) {
		this.cvService = service;
	}
	public void setCompanyDaoImpl(CompanyDao dao) {
		this.companyDao = dao;
	}
	public void setCompanyDeptDaoImpl(CompanyDeptDao dao) {
		this.companyDeptDao = dao;
	}
	public void setCompanyDeptTitleDaoImpl(CompanyDeptTitleDao dao) {
		this.companyDeptTitleDao = dao;
	}
	public void setSearchProjectCvDaoImpl(SearchProjectCvDao dao) {
		this.searchProjectCvDao = dao;
	}
	public EntityDao getEntityDao() {
		return this.searchProjectCvDao;
	}
	
	@Transactional(readOnly=true)
	public Page findPage(SearchProjectCvQuery query) {
		return searchProjectCvDao.findPage(query);
	}
	

	@SuppressWarnings("unchecked")
	public boolean cvJoinProject(List<SearchProjectCv> projectCvs){
		//if (cvService.isProtectCv(searchProjectCv.getCvId()))  throw new RuntimeException("人选["+searchProjectCv.getCvId()+"]受到保护，无法添加为目标人选。");
		return searchProjectCvDao.cvJoinProject(projectCvs);		
	}
	public Page findProjectCvPage(SearchProjectCvQuery query){
	    return searchProjectCvDao.findProjectCvPage(query);	
	}
	public void save(SearchProjectCv SearchProjectCv) {
		//如果没有存在，则添加
		
		StringBuffer sql=new StringBuffer();
		//sql.append("select a from  SearchProjectCv a   where a.projectId=? and a.cvId=? and a.companyId=? and a.deptId=? and a.titleId=? ");
		sql.append("select a from  SearchProjectCv a   where a.projectId=? and a.cvId=?  ");
		List l=new ArrayList();
		l.add(SearchProjectCv.getProjectId());
		l.add(SearchProjectCv.getCvId());
		//l.add(SearchProjectCv.getCompanyId());
		//l.add(SearchProjectCv.getDeptId());
		//l.add(SearchProjectCv.getTitleId());
		List spcvs=searchProjectCvDao.getHibernateTemplate().find(sql.toString(), l.toArray());
		if (spcvs==null||spcvs.size()<1){
			
			searchProjectCvDao.save(SearchProjectCv);
		}
		//如果在companyCv里没有，则添加
		
		if (SearchProjectCv.getCvId()!=null&&SearchProjectCv.getCompanyId()!=null&&SearchProjectCv.getDeptId()!=null&&SearchProjectCv.getTitleId()!=null){
			sql=new StringBuffer();
			sql.append("select a from  CompanyCv a   where a.cvId=? and a.companyId=? and a.deptId=? and a.titleId=? ");
		    l=new ArrayList();		
			l.add(SearchProjectCv.getCvId());
			l.add(SearchProjectCv.getCompanyId());
			l.add(SearchProjectCv.getDeptId());
			l.add(SearchProjectCv.getTitleId());
			List cvs=searchProjectCvDao.getHibernateTemplate().find(sql.toString(), l.toArray());
	        if (cvs==null||cvs.size()<1){
	        	CompanyCv companyCv= new CompanyCv();
	        	companyCv.setCompanyId(SearchProjectCv.getCompanyId());
	        	companyCv.setTitleId(SearchProjectCv.getTitleId());
	        	companyCv.setDeptId(SearchProjectCv.getDeptId());
	        	companyCv.setCvId(SearchProjectCv.getCvId());
	        	companyCv.setCreator(SearchProjectCv.getCreator());
	        	companyCv.setCreateDt(new Date());
				searchProjectCvDao.getHibernateTemplate().save(companyCv);
		   }
	      //自动并设置cc项目目标公司人选
			addProjectCvByCompanyCv(SearchProjectCv.getCompanyId()); 
		}
		
		//设置公司，部门，岗位
		try{
			Cv cv=(Cv)cvDao.getById(SearchProjectCv.getCvId());
			if (cv!=null){
				//设置人选当前公司，部门,职位			
				if (SearchProjectCv.getCompanyId()!=null&&SearchProjectCv.getCompanyId().intValue()!=0) {
					Company company=(Company)companyDao.getById(SearchProjectCv.getCompanyId());
					cv.setCompany(company.getName());
				}
				if (SearchProjectCv.getDeptId()!=null&&SearchProjectCv.getDeptId().intValue()!=0) {
					CompanyDept dept=(CompanyDept)companyDeptDao.getById(SearchProjectCv.getDeptId());
					cv.setDept(dept.getName());
				}
				if (SearchProjectCv.getTitleId()!=null&&SearchProjectCv.getTitleId().intValue()!=0) {
					CompanyDeptTitle title=(CompanyDeptTitle)companyDeptTitleDao.getById(SearchProjectCv.getTitleId());
					cv.setTitle(title.getName());
				}
				cvDao.update(cv);
				cvDao.flush();
			}
		}catch(Exception ex){}
		
	}
	
	
	public void updateCvDeptTitle(SearchProjectCvQuery query) {
		// TODO Auto-generated method stub
		//cvDept
		StringBuffer sql=new StringBuffer();
		sql.append("update search_project_cv set dept_id=?,title_id=?,modifier=?,modified_dt=?  where cv_id=? and company_id=? and dept_id=? and title_id=? ");
		List l=new ArrayList();
		l.add(query.getDeptId());
		l.add(query.getTitleId());
		l.add(query.getModifier());
		l.add(new Date());
		l.add(query.getCvId());
		l.add(query.getCompanyId());
		l.add(query.getOldDeptId());
		l.add(query.getOldTitleId());
		//设置公司，部门，岗位
		try{
			Cv cv=(Cv)cvDao.getById(query.getCvId());
			if (cv!=null){
				//设置人选当前公司，部门,职位			
				if (query.getCompanyId()!=null&&query.getCompanyId().intValue()!=0) {
					Company company=(Company)companyDao.getById(query.getCompanyId());
					cv.setCompany(company.getName());
				}
				if (query.getDeptId()!=null&&query.getDeptId().intValue()!=0) {
					CompanyDept dept=(CompanyDept)companyDeptDao.getById(query.getDeptId());
					cv.setDept(dept.getName());
				}
				if (query.getTitleId()!=null&&query.getTitleId().intValue()!=0) {
					CompanyDeptTitle title=(CompanyDeptTitle)companyDeptTitleDao.getById(query.getTitleId());
					cv.setTitle(title.getName());
				}
				cvDao.update(cv);
			}
		}catch(Exception ex){}
		
		searchProjectCvDao.getJdbcDao().update(sql.toString(), l.toArray());
		
		
	}
	private boolean checkDeleteCompanyCvAuth(SearchProjectCvQuery query){
        	
		OnlineUser onlineUser=query.getOnlineUser();
		if (onlineUser!=null){
			StringBuffer sqlSelect=new StringBuffer();
			sqlSelect.append("from SearchProjectCv a  where a.cvId=? and compayId=? and deptId=? and titleId=? ");
			List lSelect=new ArrayList();		
			lSelect.add(query.getCvId());
			lSelect.add(query.getCompanyId());
			lSelect.add(query.getDeptId());
			lSelect.add(query.getTitleId());
			List querySearchProjectCv=this.getEntityDao().getHibernateTemplate().find(sqlSelect.toString(), lSelect.toArray());
			if(SystemUserCache.isRole(onlineUser.getId(), new Integer(6))) return true;
			SearchProjectCv one=null;
			for (int i=0;querySearchProjectCv!=null&&i<querySearchProjectCv.size();i++){
				one=(SearchProjectCv)querySearchProjectCv.get(i);
				String creator=one.getCreator();
				if (creator==null) continue;				
			    if (!onlineUser.getUsername().equals(creator)) return false;
				
				
			}
		}
		return true;
	}
	private boolean checkDeleteProjectCvAuth(SearchProjectCvQuery query){
    	
		OnlineUser onlineUser=query.getOnlineUser();
		if (onlineUser!=null){
			StringBuffer sqlSelect=new StringBuffer();
			sqlSelect.append("from SearchProjectCv a  where where cvId=? and projectId=? ");
			List lSelect=new ArrayList();		
			lSelect.add(query.getCvId());
			lSelect.add(query.getCompanyId());
			lSelect.add(query.getDeptId());
			lSelect.add(query.getTitleId());
			List querySearchProjectCv=this.getEntityDao().getHibernateTemplate().find(sqlSelect.toString(), lSelect.toArray());
			if(SystemUserCache.isRole(onlineUser.getId(), new Integer(6))) return true;
			SearchProjectCv one=null;
			for (int i=0;querySearchProjectCv!=null&&i<querySearchProjectCv.size();i++){
				one=(SearchProjectCv)querySearchProjectCv.get(i);
				String creator=one.getCreator();
				if (creator==null) continue;				
			    if (!onlineUser.getUsername().equals(creator)) return false;
				
				
			}
		}
		return true;
	}
	
	public void deleteCv(SearchProjectCvQuery query) {
		// TODO Auto-generated method stub
		//cvDept
		
		
		//检查是否有权限	
		if (!checkDeleteCompanyCvAuth(query)){
			throw new RuntimeException("对不起，您没有操作权限!");
		}
		
		//检查，如果有该人选存在相应公司的CC记录，则不允许删除
		List values = new ArrayList();
		values.add(query.getCvId());
		values.add(query.getCompanyId());
		List cclist=this.getEntityDao().getJdbcDao().findByQuery("select 1 from search_project_cc_list a,search_project_company b where a.ref_cvid=? and a.project_id=b.project_id and b.company_id=?", values.toArray(), new MapObjectRowMapper());
		if (cclist!=null&&cclist.size()>0) {
			 throw new RuntimeException("人选存在相关的CC记录，不能删除！");
		}
		List values2 = new ArrayList();
		values2.add(query.getCvId());
		values2.add(query.getProjectId());

		List ccinterview=this.getEntityDao().getJdbcDao().findByQuery("select 1 from search_project_interview a  where  a.cv_id=? and a.project_id=?", values2.toArray(), new MapObjectRowMapper());
		if (ccinterview!=null&&ccinterview.size()>0) {
			 throw new RuntimeException("人选存在相关的面试记录，不能删除！");
		}
		
		List ccrecom=this.getEntityDao().getJdbcDao().findByQuery("select 1 from contract_job_cv_recom a ,contract_job_search_project b where a.job_id=b.job_id  and a.cv_id=? and b.project_id=?", values2.toArray(), new MapObjectRowMapper());
		if (ccrecom!=null&&ccrecom.size()>0) {
			 throw new RuntimeException("人选已被推荐记录，不能删除！");
		}
		
		StringBuffer sql=new StringBuffer();
		sql.append("delete from search_project_cv  where cv_id=? and company_id=? and dept_id=? and title_id=? ");
		List l=new ArrayList();		
		l.add(query.getCvId());
		l.add(query.getCompanyId());
		l.add(query.getDeptId());
		l.add(query.getTitleId());
		
		searchProjectCvDao.getJdbcDao().update(sql.toString(), l.toArray());
		searchProjectCvDao.flush();
		//兼容,额外删除companyCv
		StringBuffer deleteCompanyCvSql=new StringBuffer();
		deleteCompanyCvSql.append("delete from company_cv  where cv_id=? and company_id=? and dept_id=? and title_id=? ");
		searchProjectCvDao.getJdbcDao().update(deleteCompanyCvSql.toString(), l.toArray());
		searchProjectCvDao.flush();
		
	}
	
	public void deleteProjectCv(SearchProjectCvQuery query) {
		// TODO Auto-generated method stub
		//检查是否有权限	
		if (!checkDeleteProjectCvAuth(query)){
			throw new RuntimeException("对不起，您没有操作权限!");
		}
		List values2 = new ArrayList();
		values2.add(query.getCvId());
		values2.add(query.getProjectId());
		List cclist=this.getEntityDao().getJdbcDao().findByQuery("select 1 from search_project_cc_list a where a.ref_cvid=? and a.project_id=?", values2.toArray(), new MapObjectRowMapper());
		if (cclist!=null&&cclist.size()>0) {
			 throw new RuntimeException("人选存在相关的CC记录，不能删除！");
		}
		

		List ccinterview=this.getEntityDao().getJdbcDao().findByQuery("select 1 from search_project_interview a  where  a.cv_id=? and a.project_id=?", values2.toArray(), new MapObjectRowMapper());
		if (ccinterview!=null&&ccinterview.size()>0) {
			 throw new RuntimeException("人选存在相关的面试记录，不能删除！");
		}
		
		List ccrecom=this.getEntityDao().getJdbcDao().findByQuery("select 1 from contract_job_cv_recom a ,contract_job_search_project b where a.job_id=b.job_id  and a.cv_id=? and b.project_id=?", values2.toArray(), new MapObjectRowMapper());
		if (ccrecom!=null&&ccrecom.size()>0) {
			 throw new RuntimeException("人选已被推荐记录，不能删除！");
		}
		
		StringBuffer sql=new StringBuffer();
		sql.append("delete from search_project_cv  where cv_id=? and project_id=?");
		List l=new ArrayList();		
		l.add(query.getCvId());
		l.add(query.getProjectId());
		
		
		searchProjectCvDao.getJdbcDao().update(sql.toString(), l.toArray());		
		searchProjectCvDao.flush();
	}
	
	public void updateProjectCvStatus(SearchProjectCv searchProjectCv) {
		// TODO Auto-generated method stub
		//查询项目人才状态
		List values=new ArrayList();
		values.add(searchProjectCv.getProjectId());
		values.add(searchProjectCv.getCvId());
		List l=searchProjectCvDao.getHibernateTemplate().find("from SearchProjectCv t where t.projectId=? and t.cvId=? ", values.toArray());
		SearchProjectCv oldSearchProjectCv=null;
		
		if (l!=null&&l.size()>0){
			oldSearchProjectCv=(SearchProjectCv)l.get(0);			
		}else return;
		//System.out.println(searchProjectCv.getStatus()+" updateProjectCvStatus----aa1 "+oldSearchProjectCv.getStatus());
		if (oldSearchProjectCv.getStatus()==null) oldSearchProjectCv.setStatus(searchProjectCv.getStatus());
		if (searchProjectCv.getStatus()==null) return;
		
		//状态只能往前更新
		//if (oldSearchProjectCv.getStatus().intValue()>searchProjectCv.getStatus().intValue()) return;
		
		oldSearchProjectCv.setStatus(searchProjectCv.getStatus());
		//更新
		
		searchProjectCvDao.update(oldSearchProjectCv);
		searchProjectCvDao.flush();
		
	
	}
	//
	public SearchProjectInterview getSearchProjectInterviewById(Integer id)  {
		return searchProjectCvDao.getSearchProjectInterviewById(id);
	}
	
	/**
	 * 自动将目标公司的人选加入cc项目人选里（行业，职能，职级一样）
	 */
	public void addProjectCvByCompanyCv(Integer companyId) {
		
		// TODO Auto-generated method stub
		//and find_in_set(e.industry,c.industrys)
		StringBuffer sql=new StringBuffer();
		sql.append(" insert into search_project_cv(cv_id,project_id,company_id,dept_id,title_id,creator,create_dt) ");
		sql.append("  select a.cv_id,b.project_id,a.company_id,a.dept_id,a.title_id,'system',now() from company_cv a,search_project_company b,search_project c,cv d,company e ");
		sql.append(" where  a.company_id=? and  a.company_id=b.company_id and b.project_id=c.id and a.cv_id=d.id and a.company_id=e.id ");
		sql.append(" and find_in_set(d.function,c.functions)  and (find_in_set(d.level,c.levels) or c.levels is null or c.levels='') ");
		sql.append(" and not exists (select 1 from search_project_cv e where b.project_id=e.project_id and a.cv_id=e.cv_id) ");
		List values=new ArrayList();
		values.add(companyId);
		
		//int i=searchProjectCvDao.getJdbcDao().update(sql.toString(), values.toArray());
		//earchProjectCvDao.getJdbcDao().u
		int i=searchProjectCvDao.getJdbcDao().getJdbcTemplate().update(sql.toString(),values.toArray());
		//int i=searchProjectCvDao.getJdbcDao().update(sql.toString(),values.toArray());
		System.out.println("自动更新cc项目人选数：["+i+"]");
		searchProjectCvDao.flush();
		
	}
	
	public void updateProjectCvStatus(Integer jobId, Integer cvId,Integer status) {
		// TODO Auto-generated method stub
		List values=new ArrayList();
		values.add(jobId);
		List l=searchProjectCvDao.getHibernateTemplate().find("from ContractJobSearchProject t where t.jobId=? ", values.toArray());
		ContractJobSearchProject contractJobSearchProject=null;
		SearchProjectCv searchProjectCv=null;
		for (int i=0;l!=null&&i<l.size();i++){
			contractJobSearchProject=(ContractJobSearchProject)l.get(i);
			searchProjectCv=new SearchProjectCv();
			searchProjectCv.setProjectId(contractJobSearchProject.getProjectId());
			searchProjectCv.setCvId(cvId);
			searchProjectCv.setStatus(status);
			
			updateProjectCvStatus(searchProjectCv);
		}
		
	}
	@Override
	public boolean checkCvIntegrity(Integer cvId) {
		return cvDao.checkCvIntegrity(cvId);
	}
	
	
	
	
}
